<?php

namespace App\Http\Controllers\Seller;

use App\Events\OrderEvent;
use App\Library\Mall\SoldTrait;
use App\Models\Express;
use App\Models\Order;
use App\Models\PayUnderline;
use App\WeChat\Message\TemplateMessage;
use App\WeChat\WechatDefaultConfig;
use Illuminate\Http\Request;

class TradeController extends BaseController
{
    use SoldTrait, WechatDefaultConfig;
    /**
     * 已卖出的宝贝
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function sold()
    {
        $tab = $this->request->get('tab');
        $this->assign([
            'tab'=>'all',
            'order_no'=>'',
            'buyer_name'=>'',
            'trade_status'=>'',
            'pay_type'=>'',
            'title'=>'',
            'time_begin'=>'',
            'time_end'=>'',
            'wuliu_status'=>''
        ]);

        $queryParams = [];
        $query = $this->user()->solds()->with('items');
        $tab = $tab ? $tab : 'all';
        if ($tab)
        {
            $queryParams['tab'] = $tab;
            if ($tab == 'waitPay'){
                $query = $query->where('trade_status', 1);
            }elseif ($tab == 'waitSend'){
                $query = $query->where('trade_status', 2);
            }elseif ($tab == 'send'){
                $query = $query->where('trade_status', 3);
            }elseif ($tab == 'waitRate') {
                $query = $query->where('trade_status', 4)->where('buyer_rate', 0);
            }elseif ($tab == 'refunding'){
                $query = $query->where('trade_status', 5);
            }elseif ($tab == 'closed'){
                $query = $query->where('trade_status', 6);
            }
        }

        $order_no = $this->request->get('order_no');
        if ($order_no) {
            $queryParams['order_no'] = $order_no;
            $query = $query->where('order_no', $order_no);
        }

        $buyer_name = $this->request->get('buyer_name');
        if ($buyer_name) {
            $queryParams['buyer_name'] = $buyer_name;
            $query = $query->where('buyer_name', $buyer_name);
        }

        $trade_status = intval($this->request->get('trade_status'));
        if ($trade_status) {
            $queryParams['trade_status'] = $trade_status;
            $query = $query->where('trade_status', $trade_status);
        }

        $pay_type = intval($this->request->get('pay_type'));
        if ($pay_type) {
            $queryParams['pay_type'] = $pay_type;
            $query = $query->where('pay_type', $pay_type);
        }

        $wuliu_status = intval($this->request->get('wuliu_status'));
        if ($wuliu_status) {
            $queryParams['wuliu_status'] = $wuliu_status;
            switch ($wuliu_status){
                case 1:
                    $query = $query->where('shipping_status', 0);
                    break;
                case 2:
                    $query = $query->where('shipping_status', 1);
                    break;
                case 3:
                    $query = $query->where('shipping_status', 1)->where('receive_status', 1);
                    break;
                case 4:
                    $query = $query->where('trade_status', 1);
                    break;
                default:;
            }
        }

        $title = $this->request->get('title');
        if ($title) {
            $queryParams['title'] = $title;
            $query = $query->whereHas('items', function ($query) use ($title){
                return $query->where('title', 'LIKE', "%$title%");
            });
        }

        $time_begin = $this->request->get('time_begin');
        if ($time_begin){
            $queryParams['time_begin'] = $time_begin;
            $query = $query->where('created_at', '>', strtotime($time_begin));
        }

        $time_end = $this->request->get('time_end');
        if ($time_end){
            $queryParams['time_end'] = $time_end;
            $query = $query->where('created_at', '<', strtotime($time_end));
        }
        $this->assign($queryParams);

        $orders = $query->orderByDesc('order_id')->paginate(10);
        $this->assign([
            'menu'=>'sold_items',
            'orders'=>$orders,
            'pagination'=>$orders->appends($queryParams)->render(),
        ]);
        return $this->view('seller.trade.sold');
    }

    /**
     * @return \App\Library\SysMessager|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function detail()
    {
        $step = 'auction';
        $order_id = $this->request->input('order_id');
        $order = $this->user()->solds()->find($order_id);
        if ($order) {
            if ($order->trade_status == 2) {
                $step = 'pay';
            } elseif ($order->trade_status == 3) {
                $step = 'send';
            } elseif ($order->trade_status == 4 && $order->buyer_rate == 0) {
                $step = 'confirm';
            } elseif ($order->trade_status == 4 && $order->buyer_rate == 1) {
                $step = 'rate';
            }
            $items = $order->items;
            $shipping = $order->shipping;
            $invoice = $order->invoice;

            $this->assign(compact('order_id', 'order', 'items', 'shipping', 'step', 'invoice'));

            $pay_type_options = trans('mall.pay_type_options');
            $trade_status_items = __('mall.seller_trade_status_items');

            $expresses = Express::all();

            $this->assign(compact('pay_type_options', 'trade_status_items', 'expresses'));

            return $this->view('seller.trade.detail');
        } else {

            return $this->messager()->error()->message(__('mall.order does not exist'));
        }

    }

    protected function sendResponse(Order $order)
    {
        return $this->messager()->message(__('mall.delivery success'))->render();
    }

    public function payUnderline()
    {
        $order_id = $this->request->input('order_id');
        $pay_no = $this->request->input('pay_no');
        $order = $this->user()->solds()->find($order_id);

        if ($order && $pay_no)
        {
//            $order->changeToPaid();
//            $order->trade->delete();
//            $order->pay_type = 3;
//            $order->save();
//
//            event(new OrderEvent($order, 'paid'));
            if (PayUnderline::where('pay_no', $pay_no)->count())
            {
                return ajaxError(1, '支付流水重复');
            }
            PayUnderline::insert([
                'uid'=>$this->uid,
                'order_id'=>$order_id,
                'status'=>0,
                'created_at'=>time(),
                'pay_no'=>$pay_no
            ]);

            $order->pay_underline = 1;
            $order->save();
        }

        return ajaxReturn();
    }

    public function refund(Request $request)
    {
        $order_id = $request->input('order_id');
        $order = $this->user()->solds()->find($order_id);
        if ($order->refund_status == 1)
        {
            $item = $order->items()->first();
            return $this->view('seller.trade.refund1', compact('order_id', 'order', 'item'));
        }
        $refund = $order->refund()->with('express')->first();
        $refund->images = unserialize($refund->images);
        if (!is_array($refund->images))
        {
            $refund->images = [];
        }

        return $this->view('seller.trade.refund', compact('order', 'refund'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function checkRefund(Request $request)
    {

        $refund_status = $request->input('refund_status', 1);
        $seller_message = $request->input('seller_message', '');

        $order_id = $request->input('order_id');
        $order  = $this->user()->solds()->find($order_id);

        if ($order->refund_status == 1)
        {
            if ($refund_status == 1)
            {
                $order->refund_status = 2;
                $order->refund_at = time();
                $order->save();
            } else {
                $order->refund_status = 0;
                $order->refund_at = 0;
                if ($order->pay_status){
                    $order->trade_status = 2;
                }

                if ($order->shipping_status)
                {
                    $order->trade_status = 3;
                }

                if ($order->receive_status)
                {
                    $order->trade_status = 4;
                }
                $order->save();
            }

            return $this->messager()->message('退款已处理')->redirectTo(url('seller/trade/sold'))->render();
        }

        $refund = $order->refund;
        $refund->seller_message = $seller_message;
        //同意退款
        if ($refund_status == 1)
        {
            $refund->refund_status = 1;
            $refund->refund_at = time();

            $trade = $order->trade;
            if ($trade)
            {
                $res = $this->payment()->refund->byOutTradeNumber(
                    $trade->out_trade_no,
                    $refund->refund_no,
                    1,
                    1
                );
                //dd($res);
//                $res = $this->payment()->refund->byOutTradeNumber(
//                    $trade->out_trade_no,
//                    $refund->refund_no,
//                    intval($trade->total_amount*100),
//                    intval($refund->refund_amount)
//                );
            }
            $order->changeToRefunded();
            $refund->save();

            event(new OrderEvent($order, 'refunded'));
        }

        if ($refund_status == 2)
        {
            $refund->refund_status = 2;
            $refund->refund_at = time();
            $refund->save();

//            if ($order->pay_status){
//                $order->trade_status = 2;
//            }
//
//            if ($order->shipping_status)
//            {
//                $order->trade_status = 3;
//            }
//
//            if ($order->receive_status)
//            {
//                $order->trade_status = 4;
//            }
//            $order->save();
            $message = new TemplateMessage();
            $message->setTemplateId('rIC7TLRSePfQnhSl9wipe0C3Uu73mNLs9DKkBPYvZ8E');
            $message->setFirst('退款失败通知');
            $message->setDataValue('keyword1', $order->order_no);
            $message->setDataValue('keyword2', $refund->refund_amount);
            $message->setRemark('您的退款申请失败，'.$seller_message);
            $order->buyer->sendTemplateMessage($message);
        }

        return $this->messager()->message('退款已处理')->render();
    }

    public function export(Request $request)
    {
        $data = [
            [
                '订单号',
                '宝贝',
                '单价',
                '数量',
                '买家',
                '交易状态',
                '实收款',
                '交易时间',
                '收货人',
                '联系电话',
                '收货地址'
            ]
        ];

        $query = $this->user()->solds()->with(['items','shipping']);
        $order_no = $this->request->get('order_no');
        if ($order_no) {
            $query = $query->where('order_no', $order_no);
        }

        $buyer_name = $this->request->get('buyer_name');
        if ($buyer_name) {
            $query = $query->where('buyer_name', $buyer_name);
        }

        $trade_status = intval($this->request->get('trade_status'));
        if ($trade_status) {
            $query = $query->where('trade_status', $trade_status);
        }

        $pay_type = intval($this->request->get('pay_type'));
        if ($pay_type) {
            $query = $query->where('pay_type', $pay_type);
        }

        $wuliu_status = intval($this->request->get('wuliu_status'));
        if ($wuliu_status) {
            switch ($wuliu_status){
                case 1:
                    $query = $query->where('shipping_status', 0);
                    break;
                case 2:
                    $query = $query->where('shipping_status', 1);
                    break;
                case 3:
                    $query = $query->where('shipping_status', 1)->where('receive_status', 1);
                    break;
                case 4:
                    $query = $query->where('trade_status', 1);
                    break;
                default:;
            }
        }

        $title = $this->request->get('title');
        if ($title) {
            $query = $query->whereHas('items', function ($query) use ($title){
                return $query->where('title', 'LIKE', "%$title%");
            });
        }

        $time_begin = $this->request->get('time_begin');
        if ($time_begin){
            $query = $query->where('created_at', '>', strtotime($time_begin));
        }

        $time_end = $this->request->get('time_end');
        if ($time_end){
            $query = $query->where('created_at', '<', strtotime($time_end));
        }

        $trade_status_items = __('mall.seller_trade_status_items');
        $orders = $query->orderByDesc('order_id')->limit(10)->get();
        foreach ($orders as $order)
        {
            foreach ($order->items as $item)
            {
                $data[] = [
                    $order->order_no,
                    $item->title,
                    $item->price,
                    $item->quantity,
                    $order->buyer_name,
                    $trade_status_items[$order->trade_status],
                    $item->total_fee,
                    @date('Y-m-d H:i:s', $order->created_at),
                    $order->shipping->consignee,
                    $order->shipping->phone,
                    $order->shipping->province.$order->shipping->city.$order->shipping->district.$order->shipping->street
                ];
            }
        }

        return collect($data)->downloadExcel(
            'orders.xlsx',
            'Xlsx',
            true
        );
    }
}
